from fastapi import APIRouter, Request, Depends
from sqlalchemy.orm import Session
from datetime import datetime, timedelta
from pydantic import BaseModel
from database import get_db
from models import Users, UserType, Orders, OrderStatus

router = APIRouter(tags=["支付模块"], prefix="/pay")

# 套餐配置
VIP_PLANS = {
    "1": {"vip_type": "month", "days": 30, "price": 14.9},
    "2": {"vip_type": "season", "days": 180, "price": 79.9},
    "3": {"vip_type": "year", "days": 365, "price": 149.9}
}

# ========== 新增 Pydantic 模型 ==========
class PayModel(BaseModel):
    id: int
    paytype: str


# 创建订单 (JSON 方式)
@router.post("/index")
def pay_index(request: Request, data: PayModel, db: Session = Depends(get_db)):
    user_id = request.session.get("user_id")
    if not user_id:
        return {"status": 401, "msg": "请先登录"}

    user = db.query(Users).filter(Users.user_id == user_id).first()
    if not user:
        return {"status": 404, "msg": "用户不存在"}

    if str(data.id) not in VIP_PLANS:
        return {"status": 400, "msg": "错误的套餐ID"}

    plan = VIP_PLANS[str(data.id)]
    order = Orders(
        user_id=user.user_id,
        vip_type=UserType(plan["vip_type"]),
        pay_type=data.paytype,
        amount=plan["price"]
    )
    db.add(order)
    db.commit()
    db.refresh(order)

    # 返回二维码支付链接
    return {
        "status": 100,
        "msg": "订单创建成功",
        "orderid": order.order_id,
        "price": order.amount,
        "url": f"/pay/scan/{order.order_id}"
    }


# 卡密支付
class KamiModel(BaseModel):
    kami: str

@router.post("/kmpay")
def card_pay(request: Request, data: KamiModel, db: Session = Depends(get_db)):
    user_id = request.session.get("user_id")
    if not user_id:
        return {"code": 0, "msg": "请先登录"}

    user = db.query(Users).filter(Users.user_id == user_id).first()
    if not user:
        return {"code": 0, "msg": "用户不存在"}

    # 示例卡密
    valid_kami = {"VIP2025MONTH": ("month", 30), "VIP2025YEAR": ("year", 365)}
    if data.kami not in valid_kami:
        return {"code": 0, "msg": "无效卡密"}

    vip_type, days = valid_kami[data.kami]
    now = datetime.utcnow()
    if user.vip_status == 1 and user.vip_expire_at and user.vip_expire_at > now:
        user.vip_expire_at += timedelta(days=days)
    else:
        user.vip_status = 1
        user.vip_expire_at = now + timedelta(days=days)

    user.user_type = UserType(vip_type)
    user.vip_activate_type = "卡密"
    db.commit()

    return {"code": 1, "msg": f"开通会员成功，有效期至 {user.vip_expire_at}"}


# 支付状态查询
class QueryModel(BaseModel):
    outTradeNo: int

@router.post("/alipayquery")
def alipay_query(data: QueryModel, db: Session = Depends(get_db)):
    order = db.query(Orders).filter(Orders.order_id == data.outTradeNo).first()
    if not order:
        return {"status": 404, "msg": "订单不存在"}
    return {"status": order.status.value, "msg": "订单状态查询成功"}
